import {
  Controller,
  Post,
  Body,
  HttpStatus,
  HttpCode,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
// import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { ImportNovelService } from '../services/import-novel.service';
import { NovelCrawlerService } from '../services/novel-crawler.service';
import { ParseNovelDto } from '../dto/import-novel.dto';

@ApiTags('小说导入')
@Controller('import')
// @UseGuards(JwtAuthGuard)
// @ApiBearerAuth()
export class ImportController {
  constructor(
    private readonly importNovelService: ImportNovelService,
    private readonly novelCrawlerService: NovelCrawlerService,
  ) {}

  @Post('parse')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '异步解析并导入小说' })
  @ApiResponse({
    status: 200,
    description: '导入任务已启动',
  })
  @ApiResponse({
    status: 400,
    description: '导入失败',
  })
  async parseNovel(@Body() parseDto: ParseNovelDto) {
    console.log('🔥 ImportController.parseNovel 被调用了！URL:', parseDto.url);
    const result = await this.importNovelService.importNovelAsync(parseDto.url);

    if (result.success) {
      return {
        code: 200,
        message: '小说导入任务已启动，正在后台处理',
        data: {
          taskId: result.taskId,
        },
      };
    } else {
      return {
        code: 400,
        message: result.error || '导入失败',
        data: null,
      };
    }
  }

  @Post('check')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '检查链接是否支持导入' })
  @ApiResponse({
    status: 200,
    description: '检查成功',
  })
  @ApiResponse({
    status: 400,
    description: '检查失败',
  })
  async checkImportSupport(@Body() body: { url: string }) {
    const platform = this.novelCrawlerService.detectPlatform(body.url);

    if (platform) {
      return {
        code: 200,
        message: '支持该平台',
        data: {
          supported: true,
          platform: platform,
        },
      };
    } else {
      return {
        code: 200,
        message: '不支持该平台',
        data: {
          supported: false,
        },
      };
    }
  }
}